package com.example.business.service;

import cn.hutool.core.bean.BeanUtil;
import com.example.common.context.UserContext;
import com.example.common.exception.CommonBusinessException;
import com.example.common.util.AdminUtil;
import com.example.common.response.PageResponse;
import com.example.business.entity.SbOrder;
import com.example.business.entity.SbOrderExample;
import com.example.business.mapper.SbOrderMapper;
import com.example.business.request.SbOrderListRequest;
import com.example.business.response.SbOrderResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.util.SnowflakeUtil;
import com.example.business.request.SbOrderRequest;
import com.example.business.request.SbOrderSaveRequest;
import com.example.business.entity.SbOrderItem;
import com.example.business.mapper.SbOrderItemMapper;
import com.example.business.entity.ProductSku;
import com.example.business.mapper.ProductSkuMapper;
import com.example.business.entity.CartItem;
import com.example.business.entity.CartItemExample;
import com.example.business.mapper.CartItemMapper;
import java.util.ArrayList;
import com.example.business.entity.Product;
import com.example.business.mapper.ProductMapper;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SbOrderService {
    private static final Logger log = LoggerFactory.getLogger(SbOrderService.class);
    @Autowired
    SbOrderMapper sbOrderMapper;

    @Autowired
    AdminUtil adminUtil;

    @Autowired
    SbOrderItemMapper sbOrderItemMapper;
    @Autowired
    ProductSkuMapper productSkuMapper;
    @Autowired
    CartItemMapper cartItemMapper;
    @Autowired
    ProductMapper productMapper;

    public PageResponse<SbOrderResponse> list(SbOrderListRequest request) {
        SbOrderExample sbOrderExample = new SbOrderExample();
        // 按 id 字段逆序排序
        sbOrderExample.setOrderByClause("id desc");

        // 查询条件
        SbOrderExample.Criteria criteria = sbOrderExample.createCriteria();
        if (!adminUtil.isAdmin(UserContext.getUserId())) {
            // 增加查询条件：按「当前登录用户 id 字段」进行过滤
            criteria.andUserIdEqualTo(UserContext.getUserId());
        }

        // 增加查询条件：关键词搜索
        if (request.getKeyword() != null && !request.getKeyword().isEmpty()) {
            String keyword = "%" + request.getKeyword() + "%";
            criteria.andAddressLike(keyword);
        }

        PageHelper.startPage(request.getPage(), request.getSize());
        log.info("当前页码 current_page = {}", request.getPage());
        log.info("每页记录数 per_page = {}", request.getSize());

        List<SbOrder> sbOrders = sbOrderMapper.selectByExample(sbOrderExample);

        PageInfo<SbOrder> pageInfo = new PageInfo<>(sbOrders);
        log.info("总记录数 total = {}", pageInfo.getTotal());
        log.info("总页数 pages = {}", pageInfo.getPages());

        List<SbOrderResponse> list = BeanUtil.copyToList(sbOrders, SbOrderResponse.class);

        PageResponse<SbOrderResponse> pageResponse = new PageResponse<>();
        pageResponse.setTotal(pageInfo.getTotal());
        pageResponse.setList(list);

        return pageResponse;
    }

    public void save(SbOrderRequest request) {
        SbOrder sbOrder = BeanUtil.copyProperties(request, SbOrder.class);
        DateTime now = DateTime.now();
        if (ObjectUtil.isNull(sbOrder.getId()) || sbOrder.getId() == 0L) {
            sbOrder.setId(SnowflakeUtil.getId());
            sbOrder.setCreatedAt(now);
            sbOrder.setUpdatedAt(now);
            sbOrder.setUserId(UserContext.getUserId());
            sbOrderMapper.insert(sbOrder);
        } else {
            sbOrder.setUpdatedAt(now);
            sbOrderMapper.updateByPrimaryKeySelective(sbOrder);
        }
    }

    @Transactional
    public void saveFromWeb(SbOrderSaveRequest request) {
        SbOrder sbOrder = new SbOrder();
        long orderId = SnowflakeUtil.getId();
        sbOrder.setId(orderId);
        sbOrder.setNo(SnowflakeUtil.getIdToStr());
        sbOrder.setUserId(UserContext.getUserId());
        sbOrder.setAddress(request.getAddress());
        sbOrder.setRemark(request.getRemark());
        sbOrder.setTotalAmount(BigDecimal.ZERO); // 先设为0
        DateTime now = DateTime.now();
        sbOrder.setPaidAt(now);
        sbOrder.setPaymentMethod("现金");
        sbOrder.setStatus("已支付");
        sbOrder.setCreatedAt(now);

        BigDecimal totalAmount = BigDecimal.ZERO;
        List<Long> skuIdList = new ArrayList<>();
        for (SbOrderSaveRequest.Item item : request.getItems()) {
            ProductSku sku = productSkuMapper.selectByPrimaryKey(item.getProductSkuId());
            if (sku == null) {
                throw new CommonBusinessException("商品SKU不存在");
            }
            if (sku.getStock() == 0) {
                throw new CommonBusinessException("商品已售完");
            }
            Product product = productMapper.selectByPrimaryKey(sku.getProductId());
            if (product == null || (product.getOnSale() != null && !product.getOnSale())) {
                throw new CommonBusinessException("商品未上架");
            }
            if (item.getAmount() > 0 && sku.getStock() < item.getAmount()) {
                throw new CommonBusinessException("商品库存不足");
            }
            SbOrderItem orderItem = new SbOrderItem();
            orderItem.setId(SnowflakeUtil.getId());
            orderItem.setOrderId(orderId);
            orderItem.setProductSkuId(item.getProductSkuId());
            orderItem.setProductId(sku.getProductId());
            orderItem.setAmount(item.getAmount());
            orderItem.setPrice(sku.getPrice());
            orderItem.setCreatedAt(now);
            orderItem.setUpdatedAt(now);
            sbOrderItemMapper.insert(orderItem);
            totalAmount = totalAmount.add(sku.getPrice().multiply(BigDecimal.valueOf(item.getAmount())));
            skuIdList.add(item.getProductSkuId());
            // 扣减库存
            sku.setStock(sku.getStock() - item.getAmount());
            productSkuMapper.updateByPrimaryKeySelective(sku);
        }
        // 更新主订单总金额
        sbOrder.setTotalAmount(totalAmount);
        sbOrderMapper.insert(sbOrder);
        // 删除购物车中已下单的商品
        if (!skuIdList.isEmpty()) {
            CartItemExample example = new CartItemExample();
            CartItemExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(UserContext.getUserId());
            criteria.andProductSkuIdIn(skuIdList);
            cartItemMapper.deleteByExample(example);
        }
    }

    public int deleteBatch(List<Long> ids) {
        SbOrderExample sbOrderExample = new SbOrderExample();
        SbOrderExample.Criteria criteria = sbOrderExample.createCriteria();
        criteria.andIdIn(ids);
        return sbOrderMapper.deleteByExample(sbOrderExample);
    }
}
